package com.agriculture.gateway.filter;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author sgb
 * @create 2025/3/24
 */
public class IPRangeChecker {

    /**
     * 校验给定的 IP 是否属于指定的 IP 范围
     *
     * @param ip      要校验的 IP 地址，例如 "192.168.1.10"
     * @param startIp IP 范围的起始地址，例如 "192.168.1.1"
     * @param endIp   IP 范围的结束地址，例如 "192.168.1.100"
     * @return 如果 IP 属于范围则返回 true，否则返回 false
     */
    public static boolean isIpInRange(String ip, String startIp, String endIp) {
        try {
            long ipValue = ipToLong(InetAddress.getByName(ip));
            long startIpValue = ipToLong(InetAddress.getByName(startIp));
            long endIpValue = ipToLong(InetAddress.getByName(endIp));

            return ipValue >= startIpValue && ipValue <= endIpValue;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将 InetAddress 转换为长整型表示的 IP 值
     *
     * @param inetAddress InetAddress 对象
     * @return 长整型表示的 IP 值
     */
    private static long ipToLong(InetAddress inetAddress) {
        byte[] octets = inetAddress.getAddress();
        long result = 0;
        for (byte octet : octets) {
            result <<= 8;
            result |= (octet & 0xFF);
        }
        return result;
    }
}
